package cn.jbit.ams.user.realem;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import cn.jbit.ams.user.dao.UserMapper;
import cn.jbit.ams.user.pojo.User;

public class ShiroRealem extends AuthorizingRealm{

	@Autowired
	private UserMapper usermapper;

	@Override
	public String getName() {
		return "shiroRealem";
	}

	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		//获取登录时的用户名
		User user=(User) arg0.getPrimaryPrincipal();
		//通过用户名查询emp对象
	    User user1 = usermapper.dologin(user.getUserName());
		//获取对象中的权限名
		String rolename=user1.getPermission().getPname();
		//获取SimpleAuthorizationInfo对象
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
		//讲权限名放入SimpleAuthorizationInfo对象info中进行验证
		info.addStringPermission(rolename);
		//返回info
		return info;
	}

	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		// 将登录方法中存入令牌中的帐号和密码取出来 再到数据库中进行校验
		if (arg0.getPrincipal() == null) {
			return null;
		}
		// 获取用户信息
		String username = arg0.getPrincipal().toString();

		// 去数据库校验
		User user = usermapper.dologin(username);
		if (user == null) {
			throw new UnknownAccountException();

		} else {

			// 处理盐值
			ByteSource salt = ByteSource.Util.bytes(user.getUserName());

			// 这里验证authenticationToken和simpleAuthenticationInfo的信息
			SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,
					user.getPassword().toString(), salt, getName());
			return simpleAuthenticationInfo;
		}
	}

}
